<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="PHP,Swoole," />





  <link rel="alternate" href="/atom.xml" title="Ewan's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="今天在跟硬件开发的小伙伴测试的时候发现了一个非常有趣的问题，即Client 每次请求，Server 端我返回相同信息，但是有时候会出现两次或多次返回的数据堆叠到一起的现象。开始我还以为我代码写的有问题，仔细看了一下代码没问题啊，终究还是要相信科学。">
<meta name="keywords" content="PHP,Swoole">
<meta property="og:type" content="article">
<meta property="og:title" content="swoole 粘包 EOF 包头+包尾">
<meta property="og:url" content="http://www.iooeo.com/2017/08/03/swoole-粘包-EOF/index.html">
<meta property="og:site_name" content="Ewan&#39;s Blog">
<meta property="og:description" content="今天在跟硬件开发的小伙伴测试的时候发现了一个非常有趣的问题，即Client 每次请求，Server 端我返回相同信息，但是有时候会出现两次或多次返回的数据堆叠到一起的现象。开始我还以为我代码写的有问题，仔细看了一下代码没问题啊，终究还是要相信科学。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://ogpq2zwg5.bkt.clouddn.com/TCP%20%E7%B2%98%E5%8C%85.png">
<meta property="og:updated_time" content="2017-08-03T09:29:46.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="swoole 粘包 EOF 包头+包尾">
<meta name="twitter:description" content="今天在跟硬件开发的小伙伴测试的时候发现了一个非常有趣的问题，即Client 每次请求，Server 端我返回相同信息，但是有时候会出现两次或多次返回的数据堆叠到一起的现象。开始我还以为我代码写的有问题，仔细看了一下代码没问题啊，终究还是要相信科学。">
<meta name="twitter:image" content="http://ogpq2zwg5.bkt.clouddn.com/TCP%20%E7%B2%98%E5%8C%85.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.iooeo.com/2017/08/03/swoole-粘包-EOF/"/>





  <title>swoole 粘包 EOF 包头+包尾 | Ewan's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cea7ef9cbfe59c235bbe4bb0db874f5b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ewan's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Ewan's Blog | 杨依园技术博客 | 专注于PHP，涉及MySQL，Linux，Web，Nginx，Apache，Phalcon，Laravel，Redis，PostgreSql，Composer，Beanstalkd，Swoole</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-php">
          <a href="/categories/PHP/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-paper-plane"></i> <br />
            
            php
          </a>
        </li>
      
        
        <li class="menu-item menu-item-yii">
          <a href="/categories/PHP/Yii2/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-star"></i> <br />
            
            Yii2
          </a>
        </li>
      
        
        <li class="menu-item menu-item-swoole">
          <a href="/categories/PHP/Swoole/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />
            
            swoole
          </a>
        </li>
      
        
        <li class="menu-item menu-item-python">
          <a href="/categories/python/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-space-shuttle"></i> <br />
            
            python
          </a>
        </li>
      
        
        <li class="menu-item menu-item-awesome">
          <a href="/categories/awesome/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-dashboard"></i> <br />
            
            awesome
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.iooeo.com/2017/08/03/swoole-粘包-EOF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ewan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ewan's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">swoole 粘包 EOF 包头+包尾</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-03T15:20:25+08:00">
                2017-08-03
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/PHP/" itemprop="url" rel="index">
                    <span itemprop="name">PHP</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/PHP/Swoole/" itemprop="url" rel="index">
                    <span itemprop="name">Swoole</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/08/03/swoole-粘包-EOF/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/08/03/swoole-粘包-EOF/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2017/08/03/swoole-粘包-EOF/" class="leancloud_visitors" data-flag-title="swoole 粘包 EOF 包头+包尾">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>今天在跟硬件开发的小伙伴测试的时候发现了一个非常有趣的问题，即Client 每次请求，Server 端我返回相同信息，但是有时候会出现两次或多次返回的数据堆叠到一起的现象。开始我还以为我代码写的有问题，仔细看了一下代码没问题啊，终究还是要相信科学。<br><a id="more"></a><br><img src="http://ogpq2zwg5.bkt.clouddn.com/TCP%20%E7%B2%98%E5%8C%85.png" alt="tcp 粘包"><br>经我多方查证，原来我们的问题是 TCP 粘包问题，下面科普一下。</p>
<h2 id="TCP-粘包"><a href="#TCP-粘包" class="headerlink" title="TCP 粘包"></a>TCP 粘包</h2><h3 id="长连接和短连接"><a href="#长连接和短连接" class="headerlink" title="长连接和短连接"></a>长连接和短连接</h3><p>在讨论 TCP 粘包的问题前，我们先理解一下长连接和短连接。<br><code>长连接</code></p>
<blockquote>
<p>Client 与 Server 先建立通讯连接，连接建立后不断开， 然后再进行数据发送和接收。</p>
</blockquote>
<p><code>短连接</code></p>
<blockquote>
<p>Client 与 Server 每进行一次数据收发交易时才进行通讯连接，交易完毕后立即断开连接。此种方式常用于一点对多点通讯，比如多个Client连接一个Server。</p>
</blockquote>
<h3 id="什么是-TCP-粘包"><a href="#什么是-TCP-粘包" class="headerlink" title="什么是 TCP 粘包"></a>什么是 TCP 粘包</h3><p>TCP 粘包是指<em>发送方发送的若干包数据</em> 到 <em>接收方接收时粘成一包</em>，从接收缓冲区看，<em>后一包数据的头紧接着前一包数据的尾</em>。</p>
<h3 id="TCP-出现粘包的原因"><a href="#TCP-出现粘包的原因" class="headerlink" title="TCP 出现粘包的原因"></a>TCP 出现粘包的原因</h3><ul>
<li>发送方：发送方需要等缓冲区满才发送出去，造成粘包</li>
<li>接收方：接收方不及时接收缓冲区的包，造成多个包接收</li>
</ul>
<h3 id="什么时候需要处理粘包"><a href="#什么时候需要处理粘包" class="headerlink" title="什么时候需要处理粘包"></a>什么时候需要处理粘包</h3><p><code>不处理：</code></p>
<blockquote>
<ul>
<li>短连接，每次发送数据，就与对方建立连接，然后双方发送完一段数据后，就关闭连接，这样就不会出现粘包问题。</li>
<li>如果发送数据无结构，如文件传输被分成多个分组发送，也不用考虑粘包。</li>
</ul>
</blockquote>
<p><code>需处理：</code></p>
<blockquote>
<p>双方建立连接，需要在连接后一段时间内发送不同结构数据，如连接后，有好几种结构：<code>good morning</code>、<code>good evening</code>，如果发送方连续发了两个包出去，接收方可能就回收到<code>`good morninggood evening</code>很明显不是我们想要，需要处理。</p>
</blockquote>
<h2 id="Swoole-处理粘包"><a href="#Swoole-处理粘包" class="headerlink" title="Swoole 处理粘包"></a>Swoole 处理粘包</h2><p>既然了解了为什么会出现粘包现象和什么时候需要处理粘包，那下边就是想办法解决了。很显然我的需求得处理，很幸运 Swoole 已经提供了怎么解决粘包问题的方案。</p>
<h3 id="EOF-结束协议"><a href="#EOF-结束协议" class="headerlink" title="EOF 结束协议"></a>EOF 结束协议</h3><p>之前我在翻阅 Swoole 文档过程中，在看到 Server 配置选项的时候，看到过<code>open_eof_check</code>、<code>open_eof_split</code>、<code>package_eof</code>…配置的时候，搂了两眼，感觉很深奥的样子，就一眼带过了。现在才知道它们是用来干嘛的。<br>EOF，即指每一个数据包的结尾加一个EOF标记，表示数据包的结束，但是如果你的数据本身含有EOF标记，那就会造成收到的数据包不完整，所以开启EOF支持后，应避免数据中含有EOF标记。<br>Server 的 <code>open_eof_check</code>设置为<code>true</code>时，打开EOF检测，此选项将检测客户端连接发来的数据，当数据包结尾是指定的EOF字符串时才会投递给Worker进程。否则会一直拼接数据包，直到超过缓存区或者超时才会中止。当出错时swoole底层会认为是恶意连接，丢弃数据并强制关闭连接。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">$serv-&gt;set([</div><div class="line">	&apos;open_eof_check&apos; =&gt; true, //打开EOF检测</div><div class="line">	&apos;package_eof&apos; =&gt; &quot;\r\n&quot;, //设置EOF</div><div class="line">]);</div></pre></td></tr></table></figure></p>
<p>常见的Memcache/SMTP/POP等协议都是以<code>\r\n</code>结束的，就可以使用以上配置。开启后可以保证Worker进程一次性总是收到一个或者多个完整的数据包。<br>虽然Swoole 已经帮我在服务端做了 EOF 结束协议，但是你不能保证客户端会一次性发过来几条数据，这样会出现一次性接受多个数据包的问题，因为EOF检测不会从数据中间查找eof字符串，所以Worker进程可能会同时收到多个数据包，需要在应用层代码中自行explode(“\r\n”, $data) 来拆分数据包。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">public function onReceive($serv, $fd, $fromId, $data)</div><div class="line">&#123;</div><div class="line">    $datas = explode(&quot;\r\n&quot;, $data);</div><div class="line">    foreach ($datas as $data)</div><div class="line">    &#123;</div><div class="line">        if(!$data)&#123;</div><div class="line">            continue;</div><div class="line">        &#125;</div><div class="line">        echo &quot;Server received data: &#123;$data&#125;&quot; . PHP_EOL;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>虽然我们可以自己拆分数据，但是Swoole1.7.15版本增加了<code>open_eof_split</code>，支持从数据中查找EOF，并切分数据，那我们何乐而不为呐?<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$serv-&gt;set([</div><div class="line">	&apos;open_eof_check&apos; =&gt; true, //打开EOF检测</div><div class="line">    &apos;package_eof&apos; =&gt; &quot;\r\n&quot;, //设置EOF</div><div class="line">	&apos;open_eof_split&apos; =&gt; true,</div><div class="line">]);</div></pre></td></tr></table></figure></p>
<p>配置成上面这样，我们就不用自己在应用层代码中自行 <code>explode()</code>了。</p>
<h3 id="发送长度-固定包头和包尾"><a href="#发送长度-固定包头和包尾" class="headerlink" title="发送长度 固定包头和包尾"></a>发送长度 固定包头和包尾</h3><p>发送长度：发送每条数据的时候，将数据的长度一并发送，比如可以选择每条数据的前4位是数据的长度，应用层处理时可以根据长度来判断每条数据的开始和结束。<br>在这种协议下，我们的数据包的组成就是包头+包体。其中包头就是包体长度的二进制形式。比如我们本来想向服务端发送一段数据 “Just a test.” 共12个字符，现在我们要发送的数据就应该是这样的<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">pack(&apos;N&apos;, strlen(&quot;Just a test.&quot;)) . &quot;Just a test.&quot;</div></pre></td></tr></table></figure></p>
<p><code>pack()</code>函数是将数据打包成二进制字符串，也就是我们的包头部分。<br>这样的话 Server 收到一个数据包（可能是多个完整的数据包）之后，会先解出包头指定的数据长度，然后按照这个长度取出后面的数据，如果一次性收到多个数据包，依次循环，如此就能保证Worker进程可以一次性收到一个完整的数据包。<br>Swoole 为我们提供一下几个配置选项：</p>
<ul>
<li><code>open_length_check</code>：打开包长检测特性</li>
<li><code>package_length_type</code>：长度字段的类型，固定包头中用一个4字节或2字节表示包体长度，文章最后给出详细长度值的类型</li>
<li><code>package_length_offset</code>：从第几个字节开始是长度，比如包头长度为120字节，第10个字节为长度值，这里填入9（从0开始计数）</li>
<li><code>package_body_offset</code>：从第几个字节开始计算长度，比如包头为长度为120字节，第10个字节为长度值，包体长度为1000。如果长度包含包头，这里填入0，如果不包含包头，这里填入120</li>
<li><code>package_max_length</code>：最大允许的包长度。因为在一个请求包完整接收前，需要将所有数据保存在内存中，所以需要做保护。避免内存占用过大。</li>
</ul>
<p>具体配置就写这样：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">$serv-&gt;set([</div><div class="line">    &apos;open_length_check&apos;     =&gt; true,      // 开启协议解析</div><div class="line">    &apos;package_length_type&apos;   =&gt; &apos;N&apos;,     // 长度字段的类型</div><div class="line">    &apos;package_length_offset&apos; =&gt; 0,       //第几个字节是包长度的值</div><div class="line">    &apos;package_body_offset&apos;   =&gt; 4,       //第几个字节开始计算长度</div><div class="line">    &apos;package_max_length&apos;    =&gt; 81920,  //协议最大长度</div><div class="line">]);</div></pre></td></tr></table></figure></p>
<p>数据处理部分为这样：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">public function onReceive($serv, $fd, $fromId, $data)</div><div class="line">&#123;</div><div class="line">    $info = unpack(&apos;N&apos;, $data);</div><div class="line">    $len = $info[1];</div><div class="line">    $body = substr($data, - $len);</div><div class="line">    echo &quot;server received data: &#123;$body&#125;\n&quot;;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>完成这些，这种方案就算完成了。</p>
<h4 id="package-length-type-长度值的类型"><a href="#package-length-type-长度值的类型" class="headerlink" title="package_length_type 长度值的类型"></a>package_length_type 长度值的类型</h4><p>长度值的类型，接受一个字符参数，与php的pack函数一致。目前swoole支持10种类型：</p>
<ul>
<li>c：有符号、1字节</li>
<li>C：无符号、1字节</li>
<li>s ：有符号、主机字节序、2字节</li>
<li>S：无符号、主机字节序、2字节</li>
<li>n：无符号、网络字节序、2字节 (常用)</li>
<li>N：无符号、网络字节序、4字节 (常用)</li>
<li>l：有符号、主机字节序、4字节（小写L）</li>
<li>L：无符号、主机字节序、4字节（大写L）</li>
<li>v：无符号、小端字节序、2字节</li>
<li>V：无符号、小端字节序、4字节</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div align="center">
      
        <div class="copyright">
        <p><span>
        <b>本文地址：</b><a href="/2017/08/03/swoole-粘包-EOF/" title="swoole 粘包 EOF 包头+包尾">http://www.iooeo.com/2017/08/03/swoole-粘包-EOF/</a><br/><b>转载请注明出处，谢谢！</b>
        </span></p>
        </div>
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="http://ogpq2zwg5.bkt.clouddn.com/WechatIMG15.jpeg" alt="Ewan WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="http://ogpq2zwg5.bkt.clouddn.com/WechatIMG16.jpeg" alt="Ewan Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/PHP/" rel="tag"># PHP</a>
          
            <a href="/tags/Swoole/" rel="tag"># Swoole</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/03/lantern-运行时关闭终端/" rel="next" title="lantern 运行时关闭终端">
                <i class="fa fa-chevron-left"></i> lantern 运行时关闭终端
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/04/swoole-TCP服务器心跳维持方案/" rel="prev" title="swoole TCP服务器心跳维持方案">
                swoole TCP服务器心跳维持方案 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Ewan" />
          <p class="site-author-name" itemprop="name">Ewan</p>
           
              <p class="site-description motion-element" itemprop="description">The more effort ,the more lucky</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">138</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">40</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://resume.iooeo.com/" target="_blank" title="Resume">
                  
                    <i class="fa fa-fw fa-handshake-o"></i>
                  
                  Resume
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2120563685" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/yangyiyuan" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:654846126@qq.com" target="_blank" title="Email">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                  Email
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.firedata.cn/" target="_blank" title="Company">
                  
                    <i class="fa fa-fw fa-users"></i>
                  
                  Company
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://game.iooeo.com/" target="_blank" title="MyGame">
                  
                    <i class="fa fa-fw fa-gamepad"></i>
                  
                  MyGame
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.firedata.cn/" title="在职-意静科技" target="_blank">在职-意静科技</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.xd.com/" title="曾供职-心动网络" target="_blank">曾供职-心动网络</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.mobase.cn/" title="曾供职-翼成科技" target="_blank">曾供职-翼成科技</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.blueberrytech.cn/base/" title="曾供职-蓝莓盈动" target="_blank">曾供职-蓝莓盈动</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://old.tumiaoya.com/" title="白宝冰-博客" target="_blank">白宝冰-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liuxiaojia.cc/" title="刘佳-博客" target="_blank">刘佳-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.pythondev.org" title="曹帅军-博客" target="_blank">曹帅军-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.dannisi.xin" title="李丹-博客" target="_blank">李丹-博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://xcx.iooeo.com/" title="Cow's Love 工作室" target="_blank">Cow's Love 工作室</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#TCP-粘包"><span class="nav-number">1.</span> <span class="nav-text"><a href="#TCP-&#x7C98;&#x5305;" class="headerlink" title="TCP &#x7C98;&#x5305;"></a>TCP &#x7C98;&#x5305;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#长连接和短连接"><span class="nav-number">1.1.</span> <span class="nav-text"><a href="#&#x957F;&#x8FDE;&#x63A5;&#x548C;&#x77ED;&#x8FDE;&#x63A5;" class="headerlink" title="&#x957F;&#x8FDE;&#x63A5;&#x548C;&#x77ED;&#x8FDE;&#x63A5;"></a>&#x957F;&#x8FDE;&#x63A5;&#x548C;&#x77ED;&#x8FDE;&#x63A5;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是-TCP-粘包"><span class="nav-number">1.2.</span> <span class="nav-text"><a href="#&#x4EC0;&#x4E48;&#x662F;-TCP-&#x7C98;&#x5305;" class="headerlink" title="&#x4EC0;&#x4E48;&#x662F; TCP &#x7C98;&#x5305;"></a>&#x4EC0;&#x4E48;&#x662F; TCP &#x7C98;&#x5305;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TCP-出现粘包的原因"><span class="nav-number">1.3.</span> <span class="nav-text"><a href="#TCP-&#x51FA;&#x73B0;&#x7C98;&#x5305;&#x7684;&#x539F;&#x56E0;" class="headerlink" title="TCP &#x51FA;&#x73B0;&#x7C98;&#x5305;&#x7684;&#x539F;&#x56E0;"></a>TCP &#x51FA;&#x73B0;&#x7C98;&#x5305;&#x7684;&#x539F;&#x56E0;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#什么时候需要处理粘包"><span class="nav-number">1.4.</span> <span class="nav-text"><a href="#&#x4EC0;&#x4E48;&#x65F6;&#x5019;&#x9700;&#x8981;&#x5904;&#x7406;&#x7C98;&#x5305;" class="headerlink" title="&#x4EC0;&#x4E48;&#x65F6;&#x5019;&#x9700;&#x8981;&#x5904;&#x7406;&#x7C98;&#x5305;"></a>&#x4EC0;&#x4E48;&#x65F6;&#x5019;&#x9700;&#x8981;&#x5904;&#x7406;&#x7C98;&#x5305;</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Swoole-处理粘包"><span class="nav-number">2.</span> <span class="nav-text"><a href="#Swoole-&#x5904;&#x7406;&#x7C98;&#x5305;" class="headerlink" title="Swoole &#x5904;&#x7406;&#x7C98;&#x5305;"></a>Swoole &#x5904;&#x7406;&#x7C98;&#x5305;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#EOF-结束协议"><span class="nav-number">2.1.</span> <span class="nav-text"><a href="#EOF-&#x7ED3;&#x675F;&#x534F;&#x8BAE;" class="headerlink" title="EOF &#x7ED3;&#x675F;&#x534F;&#x8BAE;"></a>EOF &#x7ED3;&#x675F;&#x534F;&#x8BAE;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#发送长度-固定包头和包尾"><span class="nav-number">2.2.</span> <span class="nav-text"><a href="#&#x53D1;&#x9001;&#x957F;&#x5EA6;-&#x56FA;&#x5B9A;&#x5305;&#x5934;&#x548C;&#x5305;&#x5C3E;" class="headerlink" title="&#x53D1;&#x9001;&#x957F;&#x5EA6; &#x56FA;&#x5B9A;&#x5305;&#x5934;&#x548C;&#x5305;&#x5C3E;"></a>&#x53D1;&#x9001;&#x957F;&#x5EA6; &#x56FA;&#x5B9A;&#x5305;&#x5934;&#x548C;&#x5305;&#x5C3E;</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#package-length-type-长度值的类型"><span class="nav-number">2.2.1.</span> <span class="nav-text"><a href="#package-length-type-&#x957F;&#x5EA6;&#x503C;&#x7684;&#x7C7B;&#x578B;" class="headerlink" title="package_length_type &#x957F;&#x5EA6;&#x503C;&#x7684;&#x7C7B;&#x578B;"></a>package_length_type &#x957F;&#x5EA6;&#x503C;&#x7684;&#x7C7B;&#x578B;</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright" >
  
  &copy;  2013 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ewan</span>
  &nbsp;
  <span id="busuanzi_container_site_uv">
      <i class="fa fa-user-md"></i>
      本站访客数:<span id="busuanzi_value_site_pv"></span>
    </span>
</div>


<div class="powered-by">
  <span class="links-of-author-item">
    <a href="http://www.miitbeian.gov.cn/" target="_blank" title="备案号">
    沪ICP备17032516号-1
    </a>
  </span>
</div>

<div class="powered-by">
  <span class="links-of-author-item">
    <a href="https://github.com/yangyiyuan" target="_blank" title="GitHub">
    <i class="fa fa-github-alt"></i>
    GitHub
    </a>
  </span>
</div>

<div class="theme-info">
  <span class="links-of-author-item">
    <a href="http://www.iooeo.com/about/" target="_blank" title="杨依园">
    <i class="fa fa-fw fa-hand-o-right"></i>
    做一个有思想的开发者---杨依园
    </a>
  </span>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyt8r7gzu';
      var conf = 'a4830425918b568a51dfe3d835fd90db';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("ilQJ7Pnw4P9y1I1cQlaOoggK-gzGzoHsz", "uwSCLmjySIQiXUJHwkhc5XdT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script></body>
</html>
